package com.example.housingRentalSystem.controller;

import com.example.housingRentalSystem.bean.House;
import com.example.housingRentalSystem.security.provider.JwtTokenProvider;
import com.example.housingRentalSystem.service.HouseService;
import com.example.housingRentalSystem.utils.ApiResponse;
import com.example.housingRentalSystem.utils.HttpStatus;
import com.example.housingRentalSystem.utils.PageRequest;
import com.example.housingRentalSystem.utils.PageResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author 王硕
 */
@RestController
@RequestMapping("api/houses")
public class HouseController {

    @Autowired
    private HouseService houseService;
    @Autowired
    private JwtTokenProvider jwtTokenProvider;



    private static final Logger logger = LoggerFactory.getLogger(FileController.class);


    @GetMapping("/getHouses")
    public ApiResponse<PageResponse<House>> getHouses(
            @RequestParam(required = false) String city,
            @RequestParam(required = false) String rentType,
            @RequestParam(required = false) Integer minRent,
            @RequestParam(required = false) Integer maxRent,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String order,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Integer ownerId,
            @RequestParam(required = false) Integer id,
            @RequestParam(required = false) String title,
            @ModelAttribute PageRequest pageRequest) {

        // 校验排序参数
        if (sortBy != null && !List.of("monthRent", "createTime").contains(sortBy)) {
            return ApiResponse.error(400, "非法的排序字段");
        }
        if (order != null && !List.of("asc", "desc").contains(order.toLowerCase())) {
            return ApiResponse.error(400, "非法的排序方向");
        }

        pageRequest.validate();
        PageResponse<House> result = houseService.selectHouse(
                city, rentType, minRent, maxRent,
                sortBy, order, status, ownerId, id,title,
                pageRequest
        );
        logger.debug("查询结果: {}", result.getData());
        return ApiResponse.success(result);
    }

    @GetMapping("/getHousesByOwnerId")
    public ApiResponse<List<House>> getHousesByOwnerId(@RequestParam(required = false) Integer ownerId) {
        if (ownerId != null) {
            List<House> houses = houseService.selectHouseByOwnerId(ownerId);
            return ApiResponse.success(houses);
        }
        return null;
    }

    @PostMapping(value = "/add/{userId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<String> addHouse(
            @PathVariable Integer userId,
            @Valid @RequestPart("house") House house,
            @RequestPart(value = "images", required = false) List<MultipartFile> images) {
        house.setOwnerId(userId);
        return houseService.addHouse(house, images);
    }


    @PutMapping(value = "/update/{houseId}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ApiResponse<String> updateHouse(
            @PathVariable Integer houseId,
            @Valid @RequestPart("house") House house,
            @RequestPart(value = "images", required = false) List<MultipartFile> images,
            HttpServletRequest request) {
        Integer userId = jwtTokenProvider.getUserIdFromRequest(request);
        house.setId(houseId);
        return houseService.updateHouse(userId, house, images);
    }


    @PutMapping("/updateStatus/{houseId}/{status}")
    public ApiResponse<Void> updateStatus(
            @PathVariable Integer houseId,
            @PathVariable Integer status) {
        houseService.updateHouseStatus(houseId, status);
        return ApiResponse.success(HttpStatus.OK.getCode(), "更新成功",null);
    }

    @GetMapping("/selectHouseCount")
    public ApiResponse<Integer> selectHouseCount() {
        int count = houseService.selectHouseCount();
        return ApiResponse.success(count);
    }

    @GetMapping("/new-this-week")
    public ApiResponse<List<Map<String, Object>>> getNewHousesCountByDayThisWeek() {
        return ApiResponse.success(houseService.getNewHousesCountByDayThisWeek());
    }
    @GetMapping("/getHousesByStatus")
    public ApiResponse<List<House>> getHousesByStatus(@RequestParam(required = false) Integer status) {
        if (status != null) {
            List<House> houses = houseService.selectHouseByStatus(status);
            return ApiResponse.success(houses);
        }
        return null;
    }
}